package userserv

import (
	"codedef"
	"config"
	"fmt"
	"gentk"
	"log"
	"net/http"
	"userws"
	"vesync-guard"
)

var (
	myMux = &myHttpServerMux{muxHandlers: http.NewServeMux(), ignoreToken: make(map[string]bool)}
)

type myHttpServerMux struct {
	muxHandlers *http.ServeMux
	ignoreToken map[string]bool
}

func (mux *myHttpServerMux) ServeHTTP(w http.ResponseWriter, r *http.Request) {
	var path = r.URL.Path

	handler, pattern := mux.muxHandlers.Handler(r)
	log.Println("http pattern:", pattern)

	if path == "/purifiersStatus" || path == "/purifiersStatuss" {
		userws.AcceptWebsocket_purifiers(w, r)
		return
	}

	if handler == nil || pattern == "" {
		log.Printf("no handler for Request, path:%s\n", path)
		//w.WriteHeader(404)
		w.Write([]byte("404"))
		return
	}

	ignore, ok := mux.ignoreToken[pattern]
	if ok && ignore {
		handler.ServeHTTP(w, r)
		return
	}

	var uniqueId, tok = gentk.VerifyToken(r)
	if !tok {
		log.Println("token expired, path is:", path)
		replyError(w, codedef.ERR_TOKEN_EXPIRED)
		return
	}

	r.Header.Add("uniqueId", uniqueId)
	handler.ServeHTTP(w, r)
}

func CreateHttpServer() {
	go acceptHttpRequest()

	go acceptHttpsRequest()
}

func accptHttpRequest_new() {
	portStr := fmt.Sprintf(":%d", config.UServerPort)

	s := guard.NewServer(portStr, myMux)
	log.Printf("Http server listen at:%d\n", config.UServerPort)

	err := s.ListenAndServe()
	if err != nil {
		log.Println("Http server ListenAndServe 4002 failed:", err)
	}
}

func acceptHttpRequest() {
	portStr := fmt.Sprintf(":%d", config.UServerPort)
	s := &http.Server{
		Addr:    portStr,
		Handler: myMux,
		// ReadTimeout:    10 * time.Second,
		//WriteTimeout:   120 * time.Second,
		MaxHeaderBytes: 1 << 8,
	}

	log.Printf("Http server listen at:%d\n", config.UServerPort)

	err := s.ListenAndServe()
	if err != nil {
		log.Println("Http server ListenAndServe 4002 failed:", err)
	}

}

func acceptHttpsRequest() {
	portStr := fmt.Sprintf(":%d", config.UServerPortHttps)
	s := &http.Server{
		Addr:    portStr,
		Handler: myMux,
		// ReadTimeout:    10 * time.Second,
		//WriteTimeout:   120 * time.Second,
		MaxHeaderBytes: 1 << 8,
	}

	// httpsPortStr := fmt.Sprintf(":%d", config.UServerPort+3)
	// s.Addr = httpsPortStr

	certPath := fmt.Sprintf("%s%s", config.CertificatesDirectory, "/httpsCert.pem")
	keyPath := fmt.Sprintf("%s%s", config.CertificatesDirectory, "/httpsKey.pem")

	log.Printf("Https server listen at:%d\n", config.UServerPortHttps)

	err := s.ListenAndServeTLS(certPath, keyPath)
	if err != nil {
		log.Println("Https server ListenAndServe 4005 failed:", err)
	}

}
